package cn.edu.baiyunu.myapplication.data.repository

import cn.edu.baiyunu.myapplication.data.db.dao.UserPreferenceDao
import cn.edu.baiyunu.myapplication.data.db.entity.UserPreference
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach

class PreferenceRepositoryImpl(
    private val userPreferenceDao: UserPreferenceDao
) : PreferenceRepository {
    
    override fun getUserPreference(): Flow<UserPreference> {
        return userPreferenceDao.getUserPreference()
            .map { it ?: UserPreference() }
    }
    
    override suspend fun updateUserPreference(userPreference: UserPreference) {
        userPreferenceDao.insert(userPreference)
    }
    
    override fun getDefaultBackgroundColor(): Flow<String> {
        return getUserPreference().map { it.defaultBackgroundColor }
    }
    
    override suspend fun setDefaultBackgroundColor(color: String) {
        getUserPreference().onEach { currentPrefs ->
            userPreferenceDao.insert(currentPrefs.copy(defaultBackgroundColor = color))
        }
    }
    
    override fun getDefaultSpecType(): Flow<String> {
        return getUserPreference().map { it.defaultSpecType }
    }
    
    override suspend fun setDefaultSpecType(specType: String) {
        getUserPreference().onEach { currentPrefs ->
            userPreferenceDao.insert(currentPrefs.copy(defaultSpecType = specType))
        }
    }
    
    override fun getAutoOptimizeEnabled(): Flow<Boolean> {
        return getUserPreference().map { it.autoOptimizeEnabled }
    }
    
    override suspend fun setAutoOptimizeEnabled(enabled: Boolean) {
        getUserPreference().onEach { currentPrefs ->
            userPreferenceDao.insert(currentPrefs.copy(autoOptimizeEnabled = enabled))
        }
    }
} 